package com.example.backend.controller;

import com.example.backend.util.Result;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/admin")
public class AdminController {

    private static String currentAdminKey = "";
    private static LocalDateTime keyExpiryTime;

    // 每天自动生成新密钥
    @Scheduled(cron = "0 0 0 * * ?")
    private void generateNewAdminKey() {
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 12);
        currentAdminKey = "ADMIN_" + uuid;
        keyExpiryTime = LocalDateTime.now().plusDays(1);

        // 记录日志
        System.out.println("[" + LocalDateTime.now() + "] 新管理员密钥: " + currentAdminKey);
    }

    // 只有管理员可以获取密钥
    @GetMapping("/key")
    @PreAuthorize("hasAuthority('admin')")
    public Result<Map<String, String>> getAdminKey() {
        if (currentAdminKey.isEmpty()) {
            generateNewAdminKey();
        }
        Map<String, String> response = new HashMap<>();
        response.put("key", currentAdminKey);
        response.put("expiresAt", keyExpiryTime.toString());
        return Result.success(response);
    }

    // 验证密钥有效性
    @GetMapping("/validate-key")
    public Result<Boolean> validateAdminKey(@RequestParam String key) {
        boolean isValid = currentAdminKey.equals(key);
        return Result.success(isValid);
    }
}
